package server;

import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;

public class ServerEngine implements Runnable {
	private LinkedList<Integer> availablePorts;
	private int startPort;
	private int stopPort;
	private int connectPort;
	private Thread thread;
	private ServerSocket serverSocket;
	private ObjectOutputStream out;
	
	public ServerEngine(){
		startPort = 5001;
		stopPort = 5005;
		connectPort = 5000;
		GenerateAvailablePorts();
		thread = new Thread(this);
		thread.start();
		
		
	}
	
	private void GenerateAvailablePorts(){
		availablePorts = new LinkedList<Integer>();
		for(int i = startPort; i <= stopPort; i++){
			availablePorts.add(i);	
		}
	}
	
	public int getPortFromList(){
		return availablePorts.poll();
	}
	
	
	public void returnPortToList(int port){
	availablePorts.push(port);	
	}
	
	public void portToClient(Socket client, int port){
		try{
			out = new ObjectOutputStream(client.getOutputStream());
			out.writeObject(port);
		}
		catch(Exception e){
			System.out.println("Problems in -portToClient-");	
		}
	}
	

	public void run(){
		try{
			serverSocket = new ServerSocket(connectPort);
			
			while(true){
				Socket client = serverSocket.accept();
				System.out.println("Accepted a connection from: "+ client.getInetAddress());
				int port = getPortFromList();  //gets a port from the list of ports
				portToClient(client, port);		// sends the port to the client
				new ClientHandler(port);
				client.close();
			}
			
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		// new InterFace();

	}

}
